package net.xdclass.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.dto.AccountDTO;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.IllformedLocaleException;

/**
 * 小滴课堂,愿景：让技术不再难学
 *
 * @Description
 * @Author 二当家小D
 * @Remark 有问题直接联系我，源码-笔记-技术交流群
 * @Version 1.0
 **/
@Slf4j
public class JWTUtil {


    /**
     * 主题
     */
    private static final String LOGIN_SUBJECT = "XDCLASS";


    /**
     * token过期时间，7天
     */
    private static final long EXPIRED = 1000 * 60 * 60 * 24 * 7;

    private final static String SECRET_KEY = "xdclass.net168xdclass.net168xdclass.net168xdclass.net168";

    private final static SecureDigestAlgorithm<SecretKey,SecretKey> ALGORITHM = Jwts.SIG.HS256;

    private final static SecretKey KEY = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());




    /**
     * 生成token
     *
     * @param loginUser
     * @return
     */
    public static String geneJsonWebTokne(AccountDTO loginUser) {

        if (loginUser == null) {
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(LOGIN_SUBJECT)
                //配置payload
                .claim("accountId", loginUser.getId())
                .claim("username", loginUser.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(CommonUtil.getCurrentTimestamp() + EXPIRED))
                .signWith(KEY, ALGORITHM).compact();

        return addPrefix(token,LOGIN_SUBJECT) ;
    }

    private static String addPrefix(String token,String prefix) {
        return prefix+token;
    }

    private static String removePrefix(String token,String prefix) {
        if(token.startsWith(prefix)) {
            return token.replace(prefix,"").trim();
        }
        return token;
    }


    /**
     * 解密jwt
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {
            log.debug("开始校验JWT:{}",token);
            if(token == null || token.trim().isEmpty()) {
                throw new IllformedLocaleException("TOKEN不能为空");
            }
            token = token.trim();
            token = removePrefix(token,LOGIN_SUBJECT);
            log.debug("去除前缀后的TOKEN:{}",token);
            Claims payload = Jwts.parser().verifyWith(KEY)
                    .build()
                    .parseSignedClaims(token).getPayload();
            log.debug("JWT解密成功:{}",payload);
            return payload;
        } catch (Exception e) {
            log.error("jwt 解密失败");
            return null;
        }

    }


}
